<?php
declare (strict_types = 1);

namespace app\manage\controller;

use app\manage\model\PilotList;
use app\manage\model\PilotNav;
use think\App;
use think\facade\Db;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\View;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        'manage_auth'
    ];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }
    // 初始化
    protected function initialize()
    {

        $message=(new \app\manage\model\Message())->where('isopen','0')->count();
        View::assign('message', $message);
        //获取导航
        $pilot_nav=(new PilotNav())->where('isopen',1)->order('sort asc')->select();
        View::assign('pilot_nav', $pilot_nav);
        $user=Db::name('admin')->where('id',session('uid'))->find();
        $pilot_list=[];
        if($user){
            if(session('uid')!=1 or $user['role']!=1){

                $idss=(new \app\manage\model\AuthGroup())->where('id',$user['role'])->value('rules');
                $idss=explode(",", $idss);

                $idss[]=24;
                foreach ($pilot_nav as $k=>$v){
                    $arr=(new PilotList())->where('fid',0)->where('pn_id',$v['id'])->where('isopen',1)->order('sort asc')->select()->toArray();
                    foreach ($arr as $k1=>$v1){
                        $zi=(new PilotList())->where('id','in',$idss)->where('fid',$v1['id'])->where('isopen',1)->order('sort asc')->select()->toArray();
                        if($zi){
                            $arr[$k1]['zi']=$zi;
                        }
                        if(!$zi and !in_array($v1['id'],$idss)) {
                            unset($arr[$k1]);
                        }
                    }
                    $pilot_list[]=$arr;
                }
            }else{
                //侧边导航
                foreach ($pilot_nav as $k=>$v){
                    $arr=Db::name('pilot_list')->where('fid',0)->where('pn_id',$v['id'])->where('isopen',1)->order('sort asc')->select()->toArray();
                    foreach ($arr as $k1=>$v1){
                        $arr[$k1]['zi']=Db::name('pilot_list')->where('fid',$v1['id'])->where('isopen',1)->order('sort asc')->select();
                    }
                    $pilot_list[]=$arr;
                }
            }
        }
        View::assign('pilot_list', $pilot_list);
        View::assign('system', Db::name('system')->column('value','enname'));
        View::assign('is_empower', $this->empower($this->request->rootDomain(),root_path().'tpl'));
    }

    /**
     * 远程获取数据
     * @access protected
     * @param  string        $url     地址
     * @param  array        $data   post数据
     * @return array|string|true
     */
    protected function curl($url='', $data=[])
    {
        if(!$url){
            return '地址必须填写';
        }
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        if (!empty($data)) {
            $params[CURLOPT_POST] = true;
            $params[CURLOPT_POSTFIELDS] = \json_encode($data);
        }
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        if(json_decode($content, true)){
            return json_decode($content, true);
        }
        return $content;
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }
    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
        }

        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];
        $type = $this->getResponseType();
        if ($type == 'html'){
            $response = view($this->app->config->get('app.dispatch_success_tmpl'), $result);
        } else if ($type == 'json') {
            $response = json($result);
        }
        throw new HttpResponseException($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
        }

        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        $type = $this->getResponseType();
        if ($type == 'html'){
            $response = view($this->app->config->get('app.dispatch_error_tmpl'), $result);
        } else if ($type == 'json') {
            $response = json($result);
        }
        throw new HttpResponseException($response);
    }
    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
    }

    /**
     * @param null $host
     * @param null $path
     * @return bool
     */
    protected function empower($host=null, $path=null) :bool{
        if(!$host or !$path or !file_exists($path.'/code')){
            return false;
        }
        if($code=file_get_contents($path.'/code')){
            $arr=json_decode(jiemi($code),true);
            if(!isset($arr['lizhili']) or $arr['lizhili']!='lizhili'){
                return false;
            }else{
                if(in_array($host,$arr['host'])){
                    return true;
                }
            }
        }
        return false;
    }
}
